import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../core/gitcode_api.dart';

/// 仓库详情页面
/// 展示仓库的完整信息，包括描述、统计信息、所有者等
class RepositoryDetailPage extends StatefulWidget {
  const RepositoryDetailPage({
    super.key,
    required this.owner,
    required this.repo,
    this.token,
    this.projectId,
  });

  final String owner;
  final String repo;
  final String? token;
  /// 项目 ID，如果提供则优先使用 ID 查询（可避免某些仓库的路径问题）
  final int? projectId;

  @override
  State<RepositoryDetailPage> createState() => _RepositoryDetailPageState();
}

class _RepositoryDetailPageState extends State<RepositoryDetailPage> {
  final GitCodeApiClient _client = GitCodeApiClient();
  GitCodeRepositoryDetail? _repository;
  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadRepositoryDetail();
  }

  Future<void> _loadRepositoryDetail() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final repo = await _client.fetchRepository(
        widget.owner,
        widget.repo,
        personalToken: widget.token,
        projectId: widget.projectId,
      );
      setState(() {
        _repository = repo;
        _isLoading = false;
      });
    } on GitCodeApiException catch (e) {
      setState(() {
        _errorMessage = e.message;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = '加载失败：$e';
        _isLoading = false;
      });
    }
  }

  Future<void> _openUrl(String? url) async {
    if (url == null || url.isEmpty) return;
    final uri = Uri.tryParse(url);
    if (uri != null && await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(_repository?.name ?? widget.repo),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage != null
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.error_outline,
                        size: 64,
                        color: theme.colorScheme.error,
                      ),
                      const SizedBox(height: 16),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 32),
                        child: Text(
                          _errorMessage!,
                          style: TextStyle(color: theme.colorScheme.onErrorContainer),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: _loadRepositoryDetail,
                        child: const Text('重试'),
                      ),
                    ],
                  ),
                )
              : _repository == null
                  ? const Center(child: Text('仓库信息为空'))
                  : SingleChildScrollView(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 仓库名称和图标
                          Row(
                            children: [
                              Icon(
                                _repository!.isPrivate == true
                                    ? Icons.lock
                                    : Icons.folder,
                                size: 32,
                                color: theme.colorScheme.primary,
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: Text(
                                  _repository!.fullName,
                                  style: theme.textTheme.headlineSmall?.copyWith(
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),
                          // 仓库描述
                          if (_repository!.description != null &&
                              _repository!.description!.isNotEmpty) ...[
                            Text(
                              '描述',
                              style: theme.textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              _repository!.description!,
                              style: theme.textTheme.bodyMedium,
                            ),
                            const SizedBox(height: 24),
                          ],
                          // 统计信息
                          Text(
                            '统计信息',
                            style: theme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 12),
                          Wrap(
                            spacing: 12,
                            runSpacing: 12,
                            children: [
                              if (_repository!.stars != null)
                                _buildStatChip(
                                  context,
                                  'Star',
                                  _repository!.stars.toString(),
                                  Icons.star,
                                ),
                              if (_repository!.forks != null)
                                _buildStatChip(
                                  context,
                                  'Fork',
                                  _repository!.forks.toString(),
                                  Icons.call_split,
                                ),
                              if (_repository!.watchers != null)
                                _buildStatChip(
                                  context,
                                  'Watch',
                                  _repository!.watchers.toString(),
                                  Icons.visibility,
                                ),
                              if (_repository!.openIssues != null)
                                _buildStatChip(
                                  context,
                                  'Issues',
                                  _repository!.openIssues.toString(),
                                  Icons.bug_report,
                                ),
                            ],
                          ),
                          const SizedBox(height: 24),
                          // 详细信息
                          Text(
                            '详细信息',
                            style: theme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 12),
                          if (_repository!.language != null)
                            _buildInfoRow(
                              context,
                              Icons.code,
                              '主要语言',
                              _repository!.language!,
                            ),
                          if (_repository!.defaultBranch != null)
                            _buildInfoRow(
                              context,
                              Icons.account_tree,
                              '默认分支',
                              _repository!.defaultBranch!,
                            ),
                          if (_repository!.size != null)
                            _buildInfoRow(
                              context,
                              Icons.storage,
                              '仓库大小',
                              '${(_repository!.size! / 1024).toStringAsFixed(2)} MB',
                            ),
                          if (_repository!.createdAt != null)
                            _buildInfoRow(
                              context,
                              Icons.calendar_today,
                              '创建时间',
                              _formatDate(_repository!.createdAt!),
                            ),
                          if (_repository!.updatedAt != null)
                            _buildInfoRow(
                              context,
                              Icons.update,
                              '更新时间',
                              _formatDate(_repository!.updatedAt!),
                            ),
                          if (_repository!.pushedAt != null)
                            _buildInfoRow(
                              context,
                              Icons.push_pin,
                              '最后推送',
                              _formatDate(_repository!.pushedAt!),
                            ),
                          if (_repository!.license != null &&
                              _repository!.license!.name != null)
                            _buildInfoRow(
                              context,
                              Icons.gavel,
                              '许可证',
                              _repository!.license!.name!,
                            ),
                          const SizedBox(height: 24),
                          // 所有者信息
                          if (_repository!.owner != null) ...[
                            Text(
                              '所有者',
                              style: theme.textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 12),
                            Card(
                              child: ListTile(
                                leading: CircleAvatar(
                                  backgroundImage: _repository!.owner!.avatarUrl !=
                                          null
                                      ? NetworkImage(
                                          _repository!.owner!.avatarUrl!)
                                      : null,
                                  child: _repository!.owner!.avatarUrl == null
                                      ? const Icon(Icons.person)
                                      : null,
                                ),
                                title: Text(_repository!.owner!.login),
                                subtitle: _repository!.owner!.type != null
                                    ? Text(_repository!.owner!.type!)
                                    : null,
                                trailing: _repository!.owner!.htmlUrl != null
                                    ? IconButton(
                                        icon: const Icon(Icons.open_in_new),
                                        onPressed: () => _openUrl(
                                            _repository!.owner!.htmlUrl),
                                      )
                                    : null,
                              ),
                            ),
                            const SizedBox(height: 24),
                          ],
                          // 操作按钮
                          if (_repository!.htmlUrl.isNotEmpty)
                            SizedBox(
                              width: double.infinity,
                              child: ElevatedButton.icon(
                                onPressed: () => _openUrl(_repository!.htmlUrl),
                                icon: const Icon(Icons.open_in_new),
                                label: const Text('在浏览器中打开'),
                                style: ElevatedButton.styleFrom(
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 16,
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
    );
  }

  Widget _buildStatChip(
    BuildContext context,
    String label,
    String value,
    IconData icon,
  ) {
    final theme = Theme.of(context);
    return Chip(
      avatar: Icon(icon, size: 18, color: theme.colorScheme.primary),
      label: Text('$label: $value'),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
    );
  }

  Widget _buildInfoRow(
    BuildContext context,
    IconData icon,
    String label,
    String value,
  ) {
    final theme = Theme.of(context);
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Icon(icon, color: theme.colorScheme.primary),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    label,
                    style: theme.textTheme.bodySmall?.copyWith(
                      color: theme.colorScheme.onSurfaceVariant,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    value,
                    style: theme.textTheme.bodyMedium,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDate(String dateString) {
    try {
      final date = DateTime.parse(dateString);
      return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    } catch (e) {
      return dateString.length > 10
          ? dateString.substring(0, 10)
          : dateString;
    }
  }
}

